<template>
  <div class='mobile-textVote-wrapper'>
    <!-- 【注】 valid-tip-box 类名将作为paper页面的DOM索引，不能修改 -->
    <div class='valid-tip-box'
         v-if='question.validType === "required"'>
      请<span v-show='question.isMulti'>至少</span>给一个选项投票
    </div>
    <!-- 单选 -->
    <ul class='textVote-option-list' v-if='!question.isMulti'>
      <li class='option-item'
          v-for='(option, index) of question.optionList'
          :key='index'>
        <!-- 投票内容 -->
        <div class='option-box'
            :class='{ active: option.isSelected }'
            @click='selectOption(option)'>
          <div class='option-circle'></div>
          <div class='option-content' v-html='option.title'></div>
          <div class='option-desc'
              v-show='option.description'
              @click.stop='showDesc(option)'>
            ...
          </div>
        </div>
        <!-- 投票结果 -->
        <div class='option-result' :class='{show:showResult}'>
          <div class='result-slider'>
            <div class='slider-line' :style='{maxWidth: `${option.votePercentage}%`}'></div>
          </div>
          <div class='result-fake'></div>
          <div class='result-percent'>{{option.votePercentage}}%</div>
          <div class='result-count'>（{{option.voteCount}}票）</div>
        </div>
      </li>
    </ul>
    <!-- 多选 -->
    <ul class='textVote-option-list' v-if='question.isMulti'>
      <li class='option-item'
          v-for='(option, index) of question.optionList'
          :key='index'>
        <div class='option-box'
            :class='{active: option.isSelected}'
            @click='toggleOption(option)'>
          <div class='option-square'></div>
          <div class='option-content' v-html='option.title'></div>
          <div class='option-desc'
              v-show='option.description'
              @click.stop='showDesc(option)'>
            ...
          </div>
        </div>
        <!-- 投票结果 -->
        <div class='option-result' :class='{show:showResult}'>
          <div class='result-slider'>
            <div class='slider-line' :style='{maxWidth: `${option.votePercentage}%`}'></div>
          </div>
          <div class='result-fake'></div>
          <div class='result-percent'>{{option.votePercentage}}%</div>
          <div class='result-count'>（{{option.voteCount}}票）</div>
        </div>
      </li>
    </ul>
    <!-- 查看图片描述 -->
    <div class='pic-desc-wrapper'
         v-if='isShowingDesc'
         @touchmove.stop='forbitScroll'>
      <div class='desc-content'>
        <div class='desc-header'>
          <div class='desc-close iconfont' @click='hideDesc'>&#xe623;</div>
        </div>
        <div class='desc-body'>
          <div class='desc-title'>{{currVoteTitle}}</div>
          <div class='desc-box' v-html='currVoteDesc'></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'mobileTextVote',
  data () {
    return {
      currVoteTitle: '',
      currVoteDesc: '',
      isShowingDesc: false,
      showResult: false
    }
  },
  props: {
    question: {
      type: Object,
      default () {
        return {}
      }
    },
    isRecord: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    forbitScroll (e) {
      e.preventDefault()
    },
    resetValidType () {
      this.question.validType = ''
    },
    // 单选
    selectOption (opt) {
      if (this.isRecord) {
        return false
      }
      this.resetValidType()
      this.question.optionList.forEach(option => {
        if (option.optionId === opt.optionId) {
          option.isSelected = true
        } else {
          option.isSelected = false
        }
      })
      let extendAttr = JSON.parse(this.question.extendAttr || '{}')
      if (extendAttr.showVoteResult) {
        this.showResult = true
        this.updateVoteResult()
      }
    },
    // 多选
    toggleOption (opt) {
      if (this.isRecord) {
        return false
      }
      this.resetValidType()
      // 如果是选中该选项，需要判断最大选择个数
      if (this.question.selectLimit) {
        if (!opt.isSelected) {
          let selectedOptions = this.question.optionList.filter(opt => opt.isSelected)
          if (selectedOptions.length >= this.question.selectLimit) {
            return false
          }
        }
      }
      opt.isSelected = !opt.isSelected
      let extendAttr = JSON.parse(this.question.extendAttr || '{}')
      if (extendAttr.showVoteResult) {
        this.showResult = true
        this.updateVoteResult()
      }
    },
    showDesc (option) {
      this.currVoteTitle = this.formatDetail(option.title)
      this.currVoteDesc = option.description
      this.isShowingDesc = true
    },
    hideDesc () {
      this.isShowingDesc = false
    },
    formatDetail (description) {
      return description.replace(/<.*?>/g, '').slice(0, 30)
    },
    // 根据当前用户投票的选项，获取最新投票结果，并更新数据
    updateVoteResult () {
      this.$_load.show()
      // 线上
      let url = `${this.SERVICE_UPGRADE_SURVEY}/${this.question.surveyId}/vote`
      let param = {
        questionId: this.question.questionId
      }
      this.$post(url, param).then(res => {
        this.$_load.hide()
        if (res.code === 200 && res.data) {
          let voteResult = res.data
          this.question.optionList.forEach(option => {
            let targetOption = voteResult.optionStat.filter(opt => opt.optionId === option.optionId)[0]
            if (targetOption) {
              let voteCount = targetOption.voteCount
              // 如果是答题模式，需要加上自己的选择
              if (!this.isRecord) {
                option.voteCount = option.isSelected ? voteCount + 1 : voteCount
                option.votePercentage = parseInt(option.voteCount / (voteResult.voteCount + 1) * 10000) / 100
              } else {
                option.voteCount = voteCount
                option.votePercentage = parseInt(option.voteCount / voteResult.voteCount * 10000) / 100
              }
            } else {
              option.voteCount = option.isSelected ? 1 : 0
              // option.votePercentage = option.isSelected ? 100 : 0
              option.votePercentage = parseInt(option.voteCount / (voteResult.voteCount + 1) * 10000) / 100
            }
          })
          // console.log('optionList: ', this.question.optionList)
        }
      }).catch(e => {
        this.$_load.hide()
      })
    },
    init () {
      // 如果是查看记录模式, 回显答题记录
      if (this.isRecord) {
        if (this.question.answer) {
          // let optionResults = this.question.answer.optionResults
          let optionResults = this.question.answer
          this.question.optionList.forEach(option => {
            let targetOption = optionResults.filter(item => item.optionId === option.optionId)[0]
            if (targetOption) {
              option.isSelected = true
            } else {
              option.isSelected = false
            }
          })
        }
        let extendAttr = JSON.parse(this.question.extendAttr || '{}')
        if (extendAttr.showVoteResult) {
          this.showResult = true
          this.updateVoteResult()
        }
      }
    }
  },
  created () {
    this.init()
  }
}
</script>

<style lang="stylus" scoped>
.mobile-textVote-wrapper
  margin-top 10px
  .valid-tip-box
    color #ef6262
    font-size 14px
    margin-bottom 5px
  .textVote-option-list
    .option-item
      position relative
      margin-bottom 8px
      &:last-child
        margin-bottom 0
      .option-box
        padding 10px
        border 1px solid #dde5ed
        border-radius 4px
        display flex
        align-items center
        box-sizing border-box
        cursor pointer
        background #fff
        &.active
          background rgba(38, 114, 255, 0.1)
          border-color #2672ff
          .option-circle
            position relative
            border-color #2672ff
            &::after
              content ''
              position absolute
              left 0
              right 0
              top 0
              bottom 0
              margin auto
              display block
              width 10px
              height 10px
              background #2672ff
              border-radius 50%
          .option-square
            position relative
            border-color #2672ff
            &::after
              content: "";
              display: inline-block;
              width: 7px;
              height: 13px;
              border-right-style: solid;
              border-bottom-style: solid;
              border-right-width: 3px;
              border-bottom-width: 3px;
              border-color #2672ff
              transform: rotate(45deg) scale(0.7) translate3d(-2px, -5px, 0)
        &.showInput
          margin-bottom 48px
        .option-circle
          flex none
          width 14px
          height 14px
          border 1px solid #dde5ed
          border-radius 50%
          margin-right 10px
        .option-square
          flex none
          width 14px
          height 14px
          border 1px solid #dde5ed
          margin-right 10px
        .option-content
          flex 1
          width 0
          line-height 1.4
          font-size 14px
          >>> img, >>> iframe, >>> video
            max-width 100%
        .option-desc
          flex none
          width 18px
          height 18px
          line-height 9px
          border-radius 50%
          text-align center
          color #2672ff
          font-size 14px
          font-weight 700
          border 1px solid #2672ff
          margin-left 10px
          transform scale(0.8)
      .option-result
        display flex
        align-items center
        opacity: 0
        height 0
        &.show
          opacity: 1
          height 30px
        .result-slider
          width 60%
          height 3px
          background rgba(38,114,255,0.2)
          .slider-line
            height 100%
            background #2672ff
            transition all linear 0.3s
            max-width 0%
        .result-fake
          flex 1
        .result-percent
          flex none
          font-size 12px
          color #2672ff
        .result-count
          flex none
          font-size 12px
          color #2672ff
  .pic-desc-wrapper
    position fixed
    top 0
    bottom 0
    left 0
    right 0
    z-index 1000
    background rgba(0,0,0,0.8)
    .desc-content
      position absolute
      left 0
      right 0
      bottom 0
      height 60%
      background #fff
      display flex
      flex-direction column
      .desc-header
        flex none
        height 36px
        display flex
        align-items center
        justify-content flex-end
        padding-right 16px
        .desc-close
          cursor pointer
      .desc-body
        flex 1
        scroll()
        width auto
        height 0
        padding 0 16px
        .desc-title
          text-align center
          margin-bottom 10px
          line-height 1.4
        .desc-box
          line-height 1.4
          >>> img, >>> iframe, >>> video
            max-width 100% !important
</style>
